package com.doghome.news.interceptor;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import com.doghome.news.annotation.CheckPermission;
import com.doghome.news.entity.User;
import com.doghome.news.utils.BizCode;
import com.doghome.news.utils.BizDto;
import com.fasterxml.jackson.databind.ObjectMapper;

@Component
public class CheckInterceptor implements HandlerInterceptor {

	@Autowired
	private StringRedisTemplate strRedisTemplate;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}

		// 判断处理器否需要验证权限
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		CheckPermission checkPermission = handlerMethod.getMethodAnnotation(CheckPermission.class);
		if (checkPermission == null) {
			return true;
		}

		// 判断用户是否登录
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		ObjectMapper objectMapper = new ObjectMapper();
		String token = request.getHeader("Authorization");
		BizDto<Map<String, Object>> bizDto = new BizDto<Map<String, Object>>();
		if (token == null || !strRedisTemplate.hasKey(token)) {
			bizDto.setCode(BizCode.NO_LOGIN);
			bizDto.setMsg("未登录");
			response.getWriter().write(objectMapper.writeValueAsString(bizDto));
			response.getWriter().flush();
			response.getWriter().close();
			return false;
		}
		
		//token延期
		if(strRedisTemplate.getExpire(token)<300) {
			strRedisTemplate.expire(token, 30, TimeUnit.MINUTES);
		}

		int[] permissions = checkPermission.permission();
		User user = objectMapper.readValue(strRedisTemplate.opsForValue().get(token), User.class);
		boolean flag = false;
		for (int x : permissions) {
			if (user.getUtype().intValue() == x) {
				flag = true;
				break;
			}
		}
		if (!flag) {
			bizDto.setCode(BizCode.NO_PERSSION);
			bizDto.setMsg("权限不足");
			response.getWriter().write(objectMapper.writeValueAsString(bizDto));
			response.getWriter().flush();
			response.getWriter().close();
			return false;
		}
		return true;
	}

}
